package cn.wizzer.app.web.modules.controllers.platform.bus;

import cn.wizzer.app.bus.modules.models.BusinessFileInfo;
import cn.wizzer.app.bus.modules.models.YJbxx;
import cn.wizzer.app.bus.modules.models.YJbxxJyxm;
import cn.wizzer.app.bus.modules.models.YJbxxLcxx;
import cn.wizzer.app.bus.modules.services.*;
import cn.wizzer.app.sys.modules.models.Sys_dict;
import cn.wizzer.app.sys.modules.models.Sys_user;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.web.commons.doc.DocUtils;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.app.web.modules.controllers.open.file.UploadController;
import cn.wizzer.app.web.modules.controllers.platform.sys.SysDictController;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.page.Pagination;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.sql.Connection;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 样品信息  虞秀斌  2019-11
 */
@IocBean
@At("/platform/bus/ypxx/jbxx")
public class YJbxxController {
    private static final Log log = Logs.get();
    @Inject
    private YJbxxService yjbxxService;
    @Inject
    private YJbxxLcxxService yjbxxlcxxservice;
    @Inject
    private YJbxxLzxxService yjbxxlzxxservice;
    @Inject
    private SysUnitService sysUnitService;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private YJbxxSfjlService yjbxxsfjlservice;
    @Inject
    private YJbxxJyxmService yjbxxjyxmservice;

    @Inject
    private BusinessFileInfoService businessFileInfoService;


    @At("")
    @Ok("beetl:/platform/bus/ypxx/jbxx/list.html")
    @RequiresPermissions("bus.ypxx.jbxx.list")
    public void index(HttpServletRequest req) {
        req.setAttribute("userId", StringUtil.getPlatformUid());
        req.setAttribute("jylxMap", JSONObject.fromObject(sysDictService.getCodeMap("jylx")));
        req.setAttribute("lcztMap", JSONObject.fromObject(sysDictService.getCodeMap("lczt")));
        req.setAttribute("lzztMap", JSONObject.fromObject(sysDictService.getCodeMap("lzzt")));
        req.setAttribute("lcztOptions", JSONArray.fromObject(sysDictService.dictCodeTree("lczt")));
        req.setAttribute("lzztOptions", JSONArray.fromObject(sysDictService.dictCodeTree("lzzt")));
    }

    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    @RequiresPermissions("bus.ypxx.jbxx")
    public Object data(@Param("searchKeyword") String searchKeyword,@Param("lczt") String lczt,@Param("lzzt") String lzzt, @Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            String sql ="SELECT jbxx.id,jbxx.lzzt,jbxx.lczt, jbxx.ypbh,jbxx.bgbh, jbxx.ypmc,jbxx.status, jbxx.jylx, jbxx.jyks, jbxx.wtdw, jbxx.ggxh, jbxx.scrqpc, jbxx.sb, jbxx.wcqx, '' AS sysj, jbxx.jyfy, sfjl.ysfy, sfjl.jfrq,u.username,FROM_UNIXTIME(jbxx.opAt) as tjsj,jbxx.opBy " +
                    " FROM y_jbxx jbxx LEFT JOIN ( SELECT jsfjl.ypbh, sum(jsfjl.bcss) AS ysfy, max(jsfjl.jfrq) AS jfrq FROM Y_Jbxx_sfjl jsfjl GROUP BY jsfjl.ypbh ) sfjl ON jbxx.ypbh = sfjl.ypbh " +
                    " left join sys_user u on u.id=jbxx.opBy  where 1=1 and jbxx.delflag = 0 ";
            if (Strings.isNotBlank(searchKeyword)) {
                sql+= " and (jbxx.ypbh like '%"+searchKeyword+"%' or jbxx.ypmc like '%"+searchKeyword+"%') ";
            }
            if (Strings.isNotBlank(lczt)&&!lczt.equals("")) {
                sql+= " and jbxx.lczt = '"+lczt+"' ";
            }
            if (Strings.isNotBlank(lzzt)&&!lzzt.equals("")) {
                sql+= " and jbxx.lzzt = '"+lzzt+"' ";
            }
            //只能查询自己登记的数据
            //sql+= " and jbxx.opBy = '"+StringUtil.getPlatformUid()+"' ";
            sql+= StringUtil.dataScopeFilter("jbxx");
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc,jbxx.opAt desc ";
                } else {
                    sql+= " order by "+pageOrderName+" desc,jbxx.opAt desc ";
                }
            }else{
                sql+= " order by jbxx.opAt desc ";
            }
            return Result.success().addData(yjbxxService.listPage(pageNumber,pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    public Object dataCope(@Param("ypbh") String ypbh,@Param("lczt") String lczt,@Param("ypmc") String ypmc,
                           @Param("wtdw") String wtdw,@Param("sjdw") String sjdw,@Param("ggxh") String ggxh,
                           @Param("scdw") String scdw,@Param("jyyj") String jyyj,@Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            String sql ="SELECT jbxx.id,jbxx.lzzt,jbxx.lczt, jbxx.ypbh, jbxx.ypmc, jbxx.jylx, jbxx.jyks, jbxx.wtdw, jbxx.ggxh, jbxx.scrqpc, jbxx.sb, jbxx.wcqx, '' AS sysj, jbxx.jyfy, sfjl.ysfy, sfjl.jfrq " +
                    " FROM y_jbxx jbxx LEFT JOIN ( SELECT jsfjl.ypbh, sum(jsfjl.bcss) AS ysfy, max(jsfjl.jfrq) AS jfrq FROM Y_Jbxx_sfjl jsfjl GROUP BY jsfjl.ypbh ) sfjl ON jbxx.ypbh = sfjl.ypbh where 1=1 and jbxx.delflag = 0 ";
            if (Strings.isNotBlank(ypbh)) {
                sql+= " and jbxx.ypbh like '%"+ypbh+"%' ";
            }
            if (Strings.isNotBlank(ypmc)) {
                sql+= " and jbxx.ypmc like '%"+ypmc+"%' ";
            }
            if (Strings.isNotBlank(wtdw)) {
                sql+= " and jbxx.wtdw like '%"+wtdw+"%' ";
            }
            if (Strings.isNotBlank(sjdw)) {
                sql+= " and jbxx.sjdw like '%"+sjdw+"%' ";
            }
            if (Strings.isNotBlank(ggxh)) {
                sql+= " and jbxx.ggxh like '%"+ggxh+"%' ";
            }
            if (Strings.isNotBlank(jyyj)) {
                sql+= " and jbxx.jyyj like '%"+jyyj+"%' ";
            }
            if (Strings.isNotBlank(scdw)) {
                sql+= " and jbxx.scdw like '%"+scdw+"%' ";
            }
            if (Strings.isNotBlank(lczt)&&!lczt.equals("")) {
                sql+= " and jbxx.lczt = '"+lczt+"' ";
            }
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc,jbxx.opAt desc ";
                } else {
                    sql+= " order by "+pageOrderName+" desc,jbxx.opAt desc ";
                }
            }else{
                sql+= " order by jbxx.opAt desc ";
            }
            return Result.success().addData(yjbxxService.listPage(pageNumber,pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/add")
    @Ok("beetl:/platform/bus/ypxx/jbxx/add.html")
    @RequiresPermissions("bus.ypxx.jbxx.add")
    public void toadd(HttpServletRequest req,@Param("id") String id) {
        if(!StringUtils.isEmpty(id)){
            //YJbxx obj = yjbxxService.fetch(id);
            YJbxx obj = yjbxxService.fetchLinks(yjbxxService.fetch(id),"yjbxxjyxm",Cnd.NEW().asc("inspectionItemOrder"));
            obj.setJyksbh("");
            obj.setJyks("");
            obj.setZh("");
            obj.setYpbh("");
            obj.setBgbh("");
            obj.setSfty("");
            obj.setTyzt("");
            obj.setJsr("");
            obj.setYjsl("");
            obj.setYjsj("");
            obj.setTysj("");
            obj.setGhsj("");
            obj.setJyrq("");
            obj.setJyjl("");
            obj.setJyqksm("");
            obj.setSfyq("");
            obj.setYqrq("");
            obj.setDyzt("");
            obj.setSfzt("");
            obj.setJyjg("");
            obj.setJywcrq("");
            obj.setByczqk("");
            obj.setDycs("");
            obj.setDysj("");
            req.setAttribute("obj",JSONObject.fromObject(obj));
            req.setAttribute("copy",true);
            List<NutMap> list = sysDictService.dictTreeChild("xzqh");
            if(StringUtils.isNotBlank(obj.getSzcs())){
                list = sysDictService.dictTreeChilds(obj.getSzcs().split(","),list);
            }
            req.setAttribute("szcsOptions", JSONArray.fromObject(list));
        }else{
            req.setAttribute("copy",false);
            req.setAttribute("obj","{}");

            List<NutMap> list = sysDictService.dictTreeChild("xzqh");
            list = sysDictService.dictTreeChilds("112,10107,1000997".split(","),list);
            req.setAttribute("szcsOptions", JSONArray.fromObject(list));
        }
        req.setAttribute("yplxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("yplx")));
        req.setAttribute("zhOptions", JSONArray.fromObject(sysDictService.dictTree("zh")));
        req.setAttribute("storageOptions", JSONArray.fromObject(sysDictService.dictTree("storage")));
        req.setAttribute("informationOptions", JSONArray.fromObject(sysDictService.dictTree("information")));
        req.setAttribute("intentionOptions", JSONArray.fromObject(sysDictService.dictTree("intention")));
        req.setAttribute("exteriorOptions", JSONArray.fromObject(sysDictService.dictTree("exterior")));
        req.setAttribute("ypczOptions", JSONArray.fromObject(sysDictService.dictTree("ypcz")));
        req.setAttribute("jylxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("jylx")));
        req.setAttribute("unitOptions", JSONArray.fromObject(sysUnitService.getJybmTree()));
        req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
    }

    //跟新厂家信息


    @At
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxx.add")
    @SLog(tag = "新建样品", msg = "样品:${args[0].ypbh}")
    public Object addDo(@Param("..") YJbxx obj) {
        try {
            obj.setOpBy(StringUtil.getPlatformUid());
            obj.setOpAt(Times.getTS());
            obj.setSfzt("0");
            obj.setDyzt("0");
            YJbxxLcxx lcObj = new YJbxxLcxx();
            lcObj.setYpbh(obj.getYpbh());
            lcObj.setLczt(obj.getLczt());
            if(StringUtils.isNotEmpty(obj.getJylx())&&!obj.getJylx().equals("jdcc")&&!obj.getJylx().equals("jbts")&&!obj.getJylx().equals("zxzz")){
                obj.setCydw("");
                obj.setCydwId("");
                obj.setCyryBy("");
                obj.setCyrq("");
                obj.setCyjs("");
                obj.setCydbh("");
                obj.setCydd("");
            }
            if(obj.getLczt().equals("0")){
                lcObj.setSpyj("样品登记，草稿");
            }else {
                int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where ypbh = '" + obj.getYpbh()+"' and delflag=0"));
                if(count>0) {//存在重复
                    return Result.error("样品编号"+obj.getYpbh()+"重复,请修改！");
                }
                lcObj.setSpyj("样品登记，提交");
            }
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    YJbxx jbObj = yjbxxService.insertWith(obj,"yjbxxjyxm");
                    lcObj.setJbxxId(jbObj.getId());
                    yjbxxlcxxservice.execute(Sqls.create("update y_jbxx_lcxx set delflag=1 where lczt>="+lcObj.getLczt()+" and jbxxid='"+jbObj.getId()+"'"));
                    yjbxxlcxxservice.insert(lcObj);
                }
            });
            yjbxxlzxxservice.clearCache();
            yjbxxlcxxservice.clearCache();
            return Result.success("新增成功！");
        } catch (Exception e) {
            return Result.error();
        }
    }


    @At("/edit/?")
    @Ok("beetl:/platform/bus/ypxx/jbxx/edit.html")
    @RequiresPermissions("bus.ypxx.jbxx.edit")
    public void edit(String id,HttpServletRequest req) {
        YJbxx obj = yjbxxService.fetchLinks(yjbxxService.fetch(id),"yjbxxjyxm",Cnd.NEW().asc("inspectionItemOrder"));
        req.setAttribute("obj",JSONObject.fromObject(obj));
        req.setAttribute("yplxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("yplx")));
        req.setAttribute("zhOptions", JSONArray.fromObject(sysDictService.dictTree("zh")));
        List<NutMap> list = sysDictService.dictTreeChild("xzqh");
        if(StringUtils.isNotBlank(obj.getSzcs())){
            list = sysDictService.dictTreeChilds(obj.getSzcs().split(","),list);
        }

        req.setAttribute("szcsOptions", JSONArray.fromObject(list));
        req.setAttribute("ypczOptions", JSONArray.fromObject(sysDictService.dictTree("ypcz")));
        req.setAttribute("jylxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("jylx")));
        req.setAttribute("unitOptions", JSONArray.fromObject(sysUnitService.getJybmTree()));
        req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
        req.setAttribute("storageOptions", JSONArray.fromObject(sysDictService.dictTree("storage")));
        req.setAttribute("informationOptions", JSONArray.fromObject(sysDictService.dictTree("information")));
        req.setAttribute("intentionOptions", JSONArray.fromObject(sysDictService.dictTree("intention")));
        req.setAttribute("exteriorOptions", JSONArray.fromObject(sysDictService.dictTree("exterior")));
    }

    @At
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxx.edit")
    @SLog(tag = "编辑样品", msg = "样品:${args[0].ypbh}")
    public Object editDo(@Param("..") YJbxx obj) {
        try {
            obj.setOpBy(StringUtil.getPlatformUid());
            obj.setOpAt(Times.getTS());
            obj.setDyzt("0");
            YJbxxLcxx lcObj = new YJbxxLcxx();
            lcObj.setJbxxId(obj.getId());
            lcObj.setYpbh(obj.getYpbh());
            lcObj.setLczt(obj.getLczt());
            if(StringUtils.isNotEmpty(obj.getJylx())&&!obj.getJylx().equals("jdcc")&&!obj.getJylx().equals("jbts")&&!obj.getJylx().equals("zxzz")){
                obj.setCydw("");
                obj.setCydwId("");
                obj.setCyryBy("");
                obj.setCyrq("");
                obj.setCyjs("");
                obj.setCydbh("");
                obj.setCydd("");
            }
            if(obj.getLczt().equals("0")){
                lcObj.setSpyj("样品修改，草稿");
            }else {
                int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where ypbh = '" + obj.getYpbh()+"' and id !='"+obj.getId()+"' and delflag=0"));
                if(count>0) {//存在重复
                    return Result.error("样品编号"+obj.getYpbh()+"重复,请修改！");
                }
                lcObj.setSpyj("样品修改，提交");
            }
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    yjbxxService.update(obj);
                    yjbxxlcxxservice.execute(Sqls.create("update y_jbxx_lcxx set delflag=1 where lczt>="+lcObj.getLczt()+" and jbxxid='"+obj.getId()+"'"));
                    yjbxxlcxxservice.insert(lcObj);
                    yjbxxjyxmservice.execute(Sqls.create("delete from y_jbxx_jyxm  where jbxxid='"+obj.getId()+"'"));
                    for(YJbxxJyxm jyxm : obj.getYjbxxjyxm()){
                        jyxm.setJbxxId(obj.getId());
                        yjbxxjyxmservice.insert(jyxm);
                    }
                }
            });
            yjbxxlzxxservice.clearCache();
            yjbxxlcxxservice.clearCache();
            return Result.success("编辑成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At("/subm/?")
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxx.subm")
    @SLog(tag = "提交样品", msg = "样品:${args[0].ypbh}")
    public Object subm(String id) {
        try {
            String[] ids = id.split(",");
            for(int i = 0;i<ids.length;i++){
                YJbxx obj = yjbxxService.fetch(ids[i]);
                //检查数据完整性
                if(StringUtils.isEmpty(obj.getJyksbh())||StringUtils.isEmpty(obj.getJyks())||StringUtils.isEmpty(obj.getZh())||
                        StringUtils.isEmpty(obj.getYpbh())||StringUtils.isEmpty(obj.getYpmc())||StringUtils.isEmpty(obj.getJylx())
                        ||StringUtils.isEmpty(obj.getYplx())||StringUtils.isEmpty(obj.getYpdj())||StringUtils.isEmpty(obj.getYpzt())
                        ||StringUtils.isEmpty(obj.getBysl())||StringUtils.isEmpty(obj.getJysl())||StringUtils.isEmpty(obj.getSzcs())
                        ||StringUtils.isEmpty(obj.getScrqpc())||StringUtils.isEmpty(obj.getGgxh())||StringUtils.isEmpty(obj.getCyry())
                        ||StringUtils.isEmpty(obj.getSb())
                        ||StringUtils.isEmpty(obj.getWtdw())||StringUtils.isEmpty(obj.getWtdwdz())||StringUtils.isEmpty(obj.getWtdwlxr())
                        ||StringUtils.isEmpty(obj.getWtdwsj())||StringUtils.isEmpty(obj.getWtdwdh())||StringUtils.isEmpty(obj.getWtdwyb())
                        ||StringUtils.isEmpty(obj.getSjdw())||StringUtils.isEmpty(obj.getSjdwdz())||StringUtils.isEmpty(obj.getSjdwlxr())
                        ||StringUtils.isEmpty(obj.getSjdwsj())||StringUtils.isEmpty(obj.getSjdwdh())||StringUtils.isEmpty(obj.getSjdwyb())
                        ||StringUtils.isEmpty(obj.getScdw())||StringUtils.isEmpty(obj.getScdwdz())||StringUtils.isEmpty(obj.getScdwlxr())
                        ||StringUtils.isEmpty(obj.getScdwsj())||StringUtils.isEmpty(obj.getScdwdh())||StringUtils.isEmpty(obj.getScdwyb())
                        ||StringUtils.isEmpty(obj.getJyxm())||StringUtils.isEmpty(obj.getJyyj())
                        ||StringUtils.isEmpty(obj.getJyfy())||StringUtils.isEmpty(obj.getJyfydd())||StringUtils.isEmpty(obj.getYhxtk())
                        ||StringUtils.isEmpty(obj.getJyhth())||StringUtils.isEmpty(obj.getJcfyry())||StringUtils.isEmpty(obj.getBgfsfs())
                        ||StringUtils.isEmpty(obj.getDyrq())||StringUtils.isEmpty(obj.getWcqx())||StringUtils.isEmpty(obj.getLimitDay())
                        ||StringUtils.isEmpty(obj.getBz())||StringUtils.isEmpty(obj.getJyfdb())
                ){
                   return Result.error("数据不完整，无法提交");
                }
                if(obj.getJylx().equals("jdcc")||obj.getJylx().equals("jbts")||obj.getJylx().equals("zxzz")){
                    if(StringUtils.isEmpty(obj.getCydbh())||StringUtils.isEmpty(obj.getCydw())
                            ||StringUtils.isEmpty(obj.getCyjs())||StringUtils.isEmpty(obj.getCydd())||StringUtils.isEmpty(obj.getCyrq())||StringUtils.isEmpty(obj.getCyryBy())){
                        return Result.error("数据不完整，无法提交");
                    }
                }
                int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where ypbh = '" + obj.getYpbh()+"' and id !='"+obj.getId()+"' and delflag=0"));
                if(count>0) {//存在重复
                    return Result.error("样品编号"+obj.getYpbh()+"重复,请修改！");
                }
            }
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    for(int i = 0;i<ids.length;i++) {
                        YJbxx obj = yjbxxService.fetch(ids[i]);
                        obj.setOpBy(StringUtil.getPlatformUid());
                        obj.setOpAt(Times.getTS());
                        obj.setLczt("1");
                        yjbxxService.updateIgnoreNull(StringUtil.setNullValue(obj));
                        YJbxxLcxx lcObj = new YJbxxLcxx();
                        lcObj.setJbxxId(obj.getId());
                        lcObj.setYpbh(obj.getYpbh());
                        lcObj.setLczt(obj.getLczt());
                        lcObj.setSpyj("样品提交");
                        yjbxxlcxxservice.execute(Sqls.create("update y_jbxx_lcxx set delflag=1 where lczt>=" + lcObj.getLczt() +" and jbxxid='"+obj.getId()+"'"));
                        yjbxxlcxxservice.insert(lcObj);
                    }
                }
            });
            yjbxxlzxxservice.clearCache();
            yjbxxlcxxservice.clearCache();
            return Result.success("提交成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At("/detail/?")
    @Ok("beetl:/platform/bus/ypxx/jbxx/detail.html")
    @RequiresAuthentication
    public void detail(String id,HttpServletRequest req) {
        //YJbxx obj = yjbxxService.fetch(id);
        YJbxx obj = yjbxxService.fetchLinks(yjbxxService.fetch(id),"yjbxxjyxm",Cnd.NEW().asc("inspectionItemOrder"));
        if(obj!=null) {
            Map userMap = sysUserService.getUserM("");
            /*if (!StringUtils.isEmpty(obj.getYjr())) {
                obj.setYjr(userMap.get(obj.getYjr()).toString());
            }
            if (!StringUtils.isEmpty(obj.getJsr())) {
                obj.setJsr(userMap.get(obj.getJsr()).toString());
            }*/
            req.setAttribute("obj", JSONObject.fromObject(obj));
            req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
            req.setAttribute("zhMap", JSONObject.fromObject(sysDictService.getIdMap("zh")));
            req.setAttribute("xzqhMap", JSONObject.fromObject(sysDictService.getIdMap("xzqh")));
            req.setAttribute("ypczMap", JSONObject.fromObject(sysDictService.getIdMap("ypcz")));
            req.setAttribute("jylxMap", JSONObject.fromObject(sysDictService.getCodeMap("jylx")));
            req.setAttribute("lcztMap", JSONObject.fromObject(sysDictService.getCodeMap("lczt")));
            req.setAttribute("lzztMap", JSONObject.fromObject(sysDictService.getCodeMap("lzzt")));

            req.setAttribute("storageMap", JSONObject.fromObject(sysDictService.getIdMap("storage")));
            req.setAttribute("informationMap", JSONObject.fromObject(sysDictService.getIdMap("information")));
            req.setAttribute("intentionMap", JSONObject.fromObject(sysDictService.getIdMap("intention")));
            req.setAttribute("exteriorMap", JSONObject.fromObject(sysDictService.getIdMap("exterior")));

            List<Record> lzxxlist = yjbxxlzxxservice.list(Sqls.create("select a.lzzt,b.username,DATE_FORMAT(from_unixtime(a.opAt),'%Y-%m-%d %H:%i:%s') as usertime,a.spyj,a.jsbz,a.nextspr,a.lzAt,a.number,a.jhwcqx,a.statusAt,a.status,a.byczqk,a.jywcrq from y_jbxx_lzxx a left join sys_user b on a.opBy = b.id where a.jbxxid='" + id + "' order by a.opAt desc"));
            req.setAttribute("lzxxlist", JSONArray.fromObject(lzxxlist));
            List<Record> lcxxlist = yjbxxlcxxservice.list(Sqls.create("select a.lczt,b.username,DATE_FORMAT(from_unixtime(a.opAt),'%Y-%m-%d %H:%i:%s') as usertime,a.spyj,a.nextspr,a.jyry from y_jbxx_lcxx a left join sys_user b on a.opBy = b.id where a.jbxxid='" + id + "' order by a.opAt desc"));
            req.setAttribute("lcxxlist", JSONArray.fromObject(lcxxlist));
            List<Record> sfxxlist = yjbxxsfjlservice.list(Sqls.create("select * from y_jbxx_sfjl where jbxxId = '"+obj.getId()+"' and delFlag = 0 order by jfrq "));
            req.setAttribute("sfxxlist", JSONArray.fromObject(sfxxlist));
        }
    }

    @At("/delete/?")
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxx.delete")
    @SLog(tag = "删除样品", msg = "样品id:${args[0]}")
    public Object delete(String id, HttpServletRequest req) {
        try {
            YJbxx obj = yjbxxService.fetch(id);
            yjbxxlzxxservice.clearCache();
            yjbxxlcxxservice.clearCache();
            req.setAttribute("ypbh", obj.getYpbh());
            yjbxxService.vDelete(id);
            return Result.success("删除成功！");
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/delete")
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxx.delete")
    @SLog(tag = "批量删除样品", msg = "IDS:${args[1].getAttribute('ids')}")
    public Object deletes(@Param("ids") String[] ids, HttpServletRequest req) {
        try {
            yjbxxService.vDelete(ids);
            yjbxxlzxxservice.clearCache();
            yjbxxlcxxservice.clearCache();
            req.setAttribute("ids", ids.toString());
            return Result.success("删除成功！");
        } catch (Exception e) {
            return Result.error();
        }
    }


    private static String getNum(int lshcd, int num) {
        String str = String.valueOf(num);
        int other = lshcd - str.length();//看看剩余长度是多少
        for (int i = 0; i < other; i++) {//给剩余长度设置为0；
            str = "0" + str;
        }
        return str;
    }
    @At("/findZh")
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxx")
    public Object findZh(@Param("zh") String zh,@Param("id") String id) {
        try {
            if(StringUtils.isNotBlank(id)&&StringUtils.isNotEmpty(id)){
                YJbxx obj = yjbxxService.fetch(id);
                if(obj.getZh().equals(zh)){
                    return Result.success().addData(obj.getYpbh());
                }
            }
            String now = DateUtil.getDate().substring(0,4);
            String bh ="";
            List<Record> codelist = yjbxxService.list(Sqls.create("select code from sys_dict where id = '"+zh+"'"));
            if(codelist.size()>0){
                bh= String.valueOf(codelist.get(0).get("code"));
            }
            String zhcode = JSONObject.fromObject(bh).get("ypbh").toString();
            zhcode = zhcode.replace("[年]",now);//替换年
            int index = zhcode.indexOf("[L");
            if(index==-1){
                return Result.error("样品编号规则配置不正确！");
            }
            int lshcd = Integer.parseInt(zhcode.substring(index+2,index+3));//获取流水号长度
            String lshzf = zhcode.substring(index,index+4);//流水号字符
            String str = "";
            for (int i = 0; i < lshcd; i++) {//给剩余长度设置为_用于模糊查询；
                str = "_" + str;
            }
            String strzh = zhcode.replace(lshzf,str);
            //String strzh =zhcode+now;
            /*String sql = "SELECT ( SELECT max(b.num) + 1 FROM ( SELECT (CAST(right(ypbh,"+lshcd+") AS SIGNED)) num FROM y_jbxx where zh = '"+zh+"' and (left(ypbh,"+strzh.length()+"))='"+strzh+"' and delflag=0) AS b WHERE b.num < a.num ) AS beginNum, " +
                    " (a.num - 1) AS endNum FROM ( SELECT (CAST(right(ypbh,"+lshcd+") AS SIGNED)) num FROM y_jbxx where zh = '"+zh+"' and (left(ypbh,"+strzh.length()+"))='"+strzh+"' and delflag=0) AS a " +
                    " WHERE a.num > ( SELECT max(b.num) + 1 FROM ( SELECT (CAST(right(ypbh,"+lshcd+") AS SIGNED)) num FROM y_jbxx where zh = '"+zh+"' and (left(ypbh,"+strzh.length()+"))='"+strzh+"' and delflag=0) AS b WHERE b.num < a.num ) ORDER BY a.num";*/
            String sql = "SELECT ( SELECT max(b.num) + 1 FROM ( SELECT (CAST(substr(ypbh,"+(index+1)+","+lshcd+") AS SIGNED)) num FROM y_jbxx where zh = '"+zh+"' and ypbh  like '"+strzh+"' and delflag=0) AS b WHERE b.num < a.num ) AS beginNum, " +
                    " (a.num - 1) AS endNum FROM ( SELECT (CAST(substr(ypbh,"+(index+1)+","+lshcd+") AS SIGNED)) num FROM y_jbxx where zh = '"+zh+"' and ypbh  like '"+strzh+"' and delflag=0) AS a " +
                    " WHERE a.num > ( SELECT max(b.num) + 1 FROM ( SELECT (CAST(substr(ypbh,"+(index+1)+","+lshcd+") AS SIGNED)) num FROM y_jbxx where zh = '"+zh+"' and ypbh  like  '"+strzh+"' and delflag=0) AS b WHERE b.num < a.num ) ORDER BY a.num";
            List<Record> listzh = yjbxxService.list(Sqls.create(sql));
            String strNum = "";//获取流水号
            //检查是否需要插号
            if(listzh.size()>0) {
                for (int i = 0; i < 1; i++) {
                    Record record = listzh.get(i);
                    int beginNum = Integer.valueOf(record.get("beginNum").toString());
                    int endNum = Integer.valueOf(record.get("endNum").toString());
                    strNum += getNum(lshcd,beginNum);
                }
            }else{
                String newzh ="0";
                List<Record> numlist = yjbxxService.list(Sqls.create("select ifnull(max(CAST(substr(ypbh,"+(index+1)+","+lshcd+") AS SIGNED)),'0') as num from y_jbxx where zh = '"+zh+"' and ypbh  like '"+strzh+"' and delflag=0"));
                if(numlist.size()>0){
                    newzh= String.valueOf(numlist.get(0).get("num"));
                }
                int j = Integer.valueOf(newzh)+1;
                strNum += getNum(lshcd,j);
            }
            zhcode = zhcode.replace(lshzf,strNum);
            return Result.success().addData(zhcode);
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/disYpbh")
    @Ok("json")
    @RequiresAuthentication
    public Object disYpbh(@Param("ypbh") String ypbh,@Param("id") String id) {
        int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where ypbh = '" + ypbh+"' and id !='"+id+"' and delflag=0"));
        if(count>0) {//存在重复
            return Result.error("样品编号"+ypbh+"重复");
        }
        return Result.success(true);
    }
    @At("/disBgbh")
    @Ok("json")
    @RequiresAuthentication
    public Object disBgbh(@Param("bgbh") String bgbh,@Param("id") String id) {
        int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where bgbh = '" + bgbh+"' and id !='"+id+"' and delflag=0"));
        if(count>0) {//存在重复
            return Result.error("报告编号"+bgbh+"重复");
        }
        return Result.success(true);
    }
    @At("/findBgbh")
    @Ok("json")
    @RequiresAuthentication
    public Object findBgbh(@Param("id") String id) {
        try {
            YJbxx obj = yjbxxService.fetch(id);
            String now = DateUtil.getDate().substring(0, 4);
            String bh = "";
            List<Record> codelist = yjbxxService.list(Sqls.create("select code from sys_dict where id = '" + obj.getZh() + "'"));
            if (codelist.size() > 0) {
                bh = String.valueOf(codelist.get(0).get("code"));
            }
            String zhcode = JSONObject.fromObject(bh).get("ypbh").toString();
            int index = zhcode.indexOf("[L");
            if (index == -1) {
                return Result.error("样品编号规则配置不正确！");
            }
            int lshcd = Integer.parseInt(zhcode.substring(index + 2, index + 3));//获取流水号长度

            String strNum = obj.getYpbh().substring(index,index+lshcd);//获取流水号,截取样品编号的流水号
            String bg_code = JSONObject.fromObject(bh).get("bgbh").toString();
            bg_code = bg_code.replace("[年]",now);//替换年
            int bg_index = bg_code.indexOf("[L");
            if (bg_index == -1) {
                return Result.error("报告编号规则配置不正确！");
            }
            int bg_lshcd = Integer.parseInt(bg_code.substring(bg_index + 2, bg_index + 3));//获取流水号长度
            strNum = getNum(bg_lshcd, Integer.valueOf(strNum));
            String bg_lshzf = bg_code.substring(bg_index, bg_index + 4);//流水号字符
            String bgbh = bg_code.replace(bg_lshzf,strNum);
            int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where bgbh = '" + bgbh+"' and delflag=0"));
            if(count>0) {//存在重复
                strNum="";
                String str = "";
                for (int i = 0; i < bg_lshcd; i++) {//给剩余长度设置为_用于模糊查询；
                    str = "_" + str;
                }
                String strzh = bg_code.replace(bg_lshzf, str);
                String sql = "SELECT ( SELECT max(b.num) + 1 FROM ( SELECT (CAST(substr(bgbh," + (bg_index + 1) + "," + bg_lshcd + ") AS SIGNED)) num FROM y_jbxx where zh = '" + obj.getZh() + "' and bgbh  like '" + strzh + "' and delflag=0) AS b WHERE b.num < a.num ) AS beginNum, " +
                        " (a.num - 1) AS endNum FROM ( SELECT (CAST(substr(bgbh," + (bg_index + 1) + "," + bg_lshcd + ") AS SIGNED)) num FROM y_jbxx where zh = '" + obj.getZh() + "' and bgbh  like '" + strzh + "' and delflag=0) AS a " +
                        " WHERE a.num > ( SELECT max(b.num) + 1 FROM ( SELECT (CAST(substr(bgbh," + (bg_index + 1) + "," + bg_lshcd + ") AS SIGNED)) num FROM y_jbxx where zh = '" + obj.getZh() + "' and bgbh  like  '" + strzh + "' and delflag=0) AS b WHERE b.num < a.num ) ORDER BY a.num";
                List<Record> listzh = yjbxxService.list(Sqls.create(sql));
                //检查是否需要插号
                if (listzh.size() > 0) {
                        Record record = listzh.get(0);
                        int beginNum = Integer.valueOf(record.get("beginNum").toString());
                        strNum += getNum(bg_lshcd, beginNum);
                } else {
                    String newzh = "0";
                    List<Record> numlist = yjbxxService.list(Sqls.create("select ifnull(max(CAST(substr(bgbh," + (bg_index + 1) + "," + bg_lshcd + ") AS SIGNED)),'0') as num from y_jbxx where zh = '" + obj.getZh() + "' and bgbh  like '" + strzh + "' and delflag=0"));
                    if (numlist.size() > 0) {
                        newzh = String.valueOf(numlist.get(0).get("num"));
                    }
                    int j = Integer.valueOf(newzh) + 1;
                    strNum += getNum(bg_lshcd, j);
                }
                bgbh = bg_code.replace(bg_lshzf, strNum);
            }
            return Result.success().addData(bgbh);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("报告编号获取失败，请联系管理员，可临时手动填写编号");
        }
    }

    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    @RequiresAuthentication
    public Object getInsData(@Param("productName") String productName,@Param("inspectionStandard") String inspectionStandard,
                             @Param("inspectionItemName") String inspectionItemName,@Param("yplx") String yplx
            , @Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            String sql =" select bii.id as insItemId,bii.insStandardId,bis.productName,bis.productTypeCode,bis.productTypeName,bis.inspectionStandard, " +
                    " bii.inspectionItemName,bii.inspectionItemOrder,bii.standardTermsNumber,bii.specification,bii.sampleCount,bii.inspectionPrice,bii.inspectionPrice as price,1 as frequency,bii.chargeStandardCode,bii.chargeStandardName,bii.countUnit, " +
                    " bii.inspectionCycle,bii.environmentStandard,bii.equipmentCode,bii.equipmentName,bii.remark " +
                    " from bus_ins_standard bis left join bus_ins_item bii on bis.id = bii.insStandardId " +
                    " where bis.disabled =0 and bis.delFlag=0 and bii.delFlag=0 ";
            if (Strings.isNotBlank(productName)) {
                sql+= " and bis.productName like '%"+productName+"%' ";
            }
            if (Strings.isNotBlank(inspectionStandard)) {
                sql+= " and bis.inspectionStandard like '%"+inspectionStandard+"%' ";
            }
            if (Strings.isNotBlank(inspectionItemName)) {
                sql+= " and bii.inspectionItemName like '%"+inspectionItemName+"%' ";
            }
            if (Strings.isNotBlank(yplx)) {
                sql+= " and bis.productTypeCode = '"+yplx+"' ";
            }
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc ";
                } else {
                    sql+= " order by "+pageOrderName+" desc ";
                }
            }else{
                sql+= " order by bii.inspectionItemOrder ";
            }
            Pagination pag = yjbxxService.listPageMap(pageNumber,pageSize, Sqls.create(sql));
            return Result.success().addData(pag);
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/createAgreement/?")
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxx")
    @SLog(tag = "委托协议书", msg = "样品id:${args[0]}")
    public Object createAgreement(String id) {
        try {
            YJbxx obj = yjbxxService.fetch(id);

            //检查数据完整性
            if(StringUtils.isEmpty(obj.getJyksbh())||StringUtils.isEmpty(obj.getJyks())||StringUtils.isEmpty(obj.getZh())||StringUtils.isEmpty(obj.getYpbh())||StringUtils.isEmpty(obj.getYpmc())||StringUtils.isEmpty(obj.getJylx())){
                return Result.error("数据不完整，无法生成委托协议书");
            }
            //获取协议书模板路径
            BusinessFileInfo agreementTemplate = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("infoName", "=", "委托协议书").and("productType","like","%"+obj.getYplx()+"%").and("disabled","=",false));
            if(agreementTemplate==null){
                return Result.error("请上传产品检验委托协议书模板后再生成产品检验委托协议书！");
            }
            String uploadPath = this.getUploadPathConfig();
            String demoAgreement = uploadPath+agreementTemplate.getFilePath();//封面和首页内容模板路径

            //获取生成的委托协议书路径
            String date= DateUtil.format(new Date(), "yyyy")+"/"+DateUtil.format(new Date(), "MM")+"/"+DateUtil.format(new Date(), "dd");
            String fileName = obj.getId()+"xys";
            String newAgreementPath = "/agreement/" + date + "/" + fileName+".docx";
            String newAgreement = uploadPath+newAgreementPath;//生成报告路径

            BusinessFileInfo oldReport = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("fileName", "=", fileName));

            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    if(oldReport!=null){
                        //先删除历史的文件
                        File old_report_file = new File(uploadPath+oldReport.getFilePath());
                        old_report_file.delete();
                        if (old_report_file.exists()) {
                            if (old_report_file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                                old_report_file.delete();
                            }
                        }
                        businessFileInfoService.delete(oldReport.getId());
                    }
                }
            });
            Map<String, String> map = new HashMap<String, String>();
            map.put("PO1_ypbh", StringUtils.isEmpty(obj.getYpbh())?"/":obj.getYpbh());
            String zh = getNames(obj.getZh(),"");
            map.put("PO1_zh",StringUtils.isEmpty(zh)?"/":zh);
            map.put("PO1_ypmc", StringUtils.isEmpty(obj.getYpmc())?"/":obj.getYpmc());
            map.put("PO1_scrqpc", StringUtils.isEmpty(obj.getScrqpc())?"/":obj.getScrqpc());
            map.put("PO1_ggxh", StringUtils.isEmpty(obj.getGgxh())?"/":obj.getGgxh());
            map.put("PO1_wtdw", StringUtils.isEmpty(obj.getWtdw())?"/":obj.getWtdw());
            map.put("PO1_sb", StringUtils.isEmpty(obj.getSb())?"/":obj.getSb());
            map.put("PO1_sjdw", StringUtils.isEmpty(obj.getSjdw())?"/":obj.getSjdw());
            /*String p2_ypsl = "" ;
            if(!StringUtils.isEmpty(obj.getBysl())){
                p2_ypsl +="备样："+obj.getBysl();
            }else{
                p2_ypsl +="备样：/";
            }
            if(!StringUtils.isEmpty(obj.getJysl())){
                p2_ypsl +="检样："+obj.getJysl();
            }else{
                p2_ypsl +="检样：/";
            }*/
            int p2_ypsl = 0 ;
            if(!StringUtils.isEmpty(obj.getBysl())){
                p2_ypsl +=Integer.valueOf(obj.getBysl());
            }
            if(!StringUtils.isEmpty(obj.getJysl())){
                p2_ypsl +=Integer.valueOf(obj.getJysl());
            }
            map.put("PO1_ypsl", p2_ypsl==0?"/":p2_ypsl+(StringUtils.isEmpty(obj.getUnit())?"":obj.getUnit()));
            map.put("PO1_ypsl2", p2_ypsl==0?"/":p2_ypsl+(StringUtils.isEmpty(obj.getUnit())?"":obj.getUnit()));
            map.put("PO1_scdw", StringUtils.isEmpty(obj.getScdw())?"/":obj.getScdw());
            map.put("PO1_ypdj", StringUtils.isEmpty(obj.getYpdj())?"/":obj.getYpdj());
            map.put("PO1_lxr", StringUtils.isEmpty(obj.getCyry())?"/":obj.getCyry());
            map.put("PO1_sj", StringUtils.isEmpty(obj.getJyfdb())?"/":obj.getJyfdb());
            map.put("PO1_wtdwyb", StringUtils.isEmpty(obj.getWtdwyb())?"/":obj.getWtdwyb());
            map.put("PO1_wtdwdz", StringUtils.isEmpty(obj.getWtdwdz())?"/":obj.getWtdwdz());
            map.put("PO1_jylx", getCodes(obj.getJylx(),"","jylx"));
            map.put("PO1_ypzt", StringUtils.isEmpty(obj.getYpzt())?"/":obj.getYpzt());
            map.put("PO1_jyyj", StringUtils.isEmpty(obj.getJyyj())?"/":obj.getJyyj());
            map.put("PO1_jyxm", StringUtils.isEmpty(obj.getJyxm())?"/":obj.getJyxm());
            String bglq = "其它";
            if(!StringUtils.isEmpty(obj.getBgfsfs())) {
                if (obj.getBgfsfs().equals("0")) {
                    bglq = "邮寄";
                } else if (obj.getBgfsfs().equals("1")) {
                    bglq = "自取";
                }
            }
            map.put("PO1_bgfsfs",  StringUtils.isEmpty(bglq)?"/":bglq);
            String ypcz = getNames(obj.getYhxtk(),"");
            map.put("PO1_ypcz", StringUtils.isEmpty(ypcz)?"/":ypcz);
            map.put("PO1_dyrq", StringUtils.isEmpty(obj.getDyrq())?"/":obj.getDyrq());
            map.put("PO1_limitDay", StringUtils.isEmpty(obj.getLimitDay())?"/":obj.getLimitDay()+"个工作日");
            //map.put("PO1_wcqx", StringUtils.isEmpty(obj.getWcqx())?"/":DateUtil.StringFormat(obj.getWcqx(),"yyyy年MM月dd日"));
            map.put("PO1_opAt", DateUtil.getDate(obj.getOpAt(),"yyyy年MM月dd日"));
            if(!StringUtils.isEmpty(obj.getJyfy())) {
                map.put("PO1_jyfy", obj.getJyfy().equals("0")?"/":obj.getJyfy()+"");
                Map sfxxmap = yjbxxsfjlservice.getMap(Sqls.create("select 'ysje' ,sum(ifnull(bcss,0)) as ysje from y_jbxx_sfjl where jbxxId = '" + obj.getId() + "' and delFlag = 0  "));
                String ysje = "0";
                if (sfxxmap != null) {
                    ysje = sfxxmap.get("ysje").toString();
                }
                if(ysje.equals("")){
                    ysje = "0";
                }
                Double sjje = Double.valueOf(obj.getJyfy())-Double.valueOf(ysje);
                map.put("PO1_ysje", ysje);
                map.put("PO1_sjje", sjje.toString());
            }

            map.put("PO1_jyyq", StringUtils.isEmpty(obj.getBz())?"/":obj.getBz());
            map.put("PO1_bz", StringUtils.isEmpty(obj.getXysRemark())?"/":obj.getXysRemark());
            map.put("PO1_validity", StringUtils.isEmpty(obj.getValidity())?"/":obj.getValidity());
            map.put("PO1_packing", StringUtils.isEmpty(obj.getPacking())?"/":obj.getPacking());
            String storage = getNames(obj.getStorage(),"");
            map.put("PO1_storage", StringUtils.isEmpty(storage)?"/":storage);
            String information = getNames(obj.getInformation(),"，");
            map.put("PO1_information", StringUtils.isEmpty(information)?"/":information);
            map.put("PO1_subcontract", StringUtils.isEmpty(obj.getSubcontract())?"/":obj.getSubcontract());
            String intention = getNames(obj.getIntention(),"");
            map.put("PO1_intention", StringUtils.isEmpty(intention)?"/":intention);
            String exterior = getNames(obj.getExterior(),"");
            map.put("PO1_exterior",  StringUtils.isEmpty(exterior)?"/":exterior);
            Sys_user slrUser = sysUserService.fetch(obj.getOpBy());
            String fileId = slrUser.getFileId();
            if(!StringUtils.isEmpty(fileId)){
                BusinessFileInfo signatureImage = businessFileInfoService.fetch(fileId);
                map.put("PO1_slr", uploadPath+signatureImage.getFilePath());
            }
            DocUtils.FileToFile2(demoAgreement,newAgreement,map,new ArrayList<>());

            BusinessFileInfo report = new BusinessFileInfo();
            report.setInfoName(fileName);
            report.setInfoVersion(date);
            report.setInfoType("report");
            report.setRemark("");
            report.setOperatorName(StringUtil.getPlatformUsername());
            report.setFileType(".docx");
            report.setDisabled(false);
            report.setFilePath(newAgreementPath);
            report.setFileName(fileName);
            report.setFileBeforeName( fileName+".docx");
            report.setFileUrl(newAgreement);
            businessFileInfoService.insert(report);
            return Result.success("生成成功！").addData(newAgreement);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("system.error");
        }
    }

    public String getNames(String ids,String spl){
        String names ="";
        if(!StringUtils.isEmpty(ids)){
            String[] id = ids.split(",");
            for(int i = 0 ; i <id.length ;i++){
                names += sysDictService.getNameById(id[i]);
                if(i<(id.length-1)){
                    names+=spl;
                }
            }
        }
        return names;
    }
    public String getCodes(String ids,String spl,String parentCode){
        String names ="";
        if(!StringUtils.isEmpty(ids)){
            String[] id = ids.split(",");
            for(int i = 0 ; i <id.length ;i++){
                names += sysDictService.getNameByCode(id[i],parentCode);
                if(i<(id.length-1)){
                    names+=spl;
                }
            }
        }
        return names;
    }
    private String getUploadPathConfig() throws Exception {
        String uploadPath;
        //系统没开启配置,上传到项目路径
        if ("false".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))){
            uploadPath= UploadController.class.getClassLoader().getResource("").getPath()+"upload";
        }else if (
                ("true".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false")))&&(Globals.MyConfig.getOrDefault("ConfigUploadPath", null)!=null)
        ){
            uploadPath=Globals.MyConfig.get("ConfigUploadPath").toString();
        }else {
            throw new Exception("文件上传路径配置有误");
        }
        return uploadPath;
    }
}
